package com.example.featuresdk.view

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layout
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.featuresdk.R
import com.example.featuresdk.theme.DemoTheme

@Composable
fun BadgeIcon(drawableIcon: Int, iconSize: Int, description: String = "",  number: Int = 0, numberVisible: Boolean = false){

    Box(Modifier.padding(if(numberVisible) 8.dp else 6.dp)) {

        Image(
            painter = painterResource(drawableIcon),
            contentDescription = description,
            modifier = Modifier.size(iconSize.dp)
                .drawWithContent {
                    drawContent()
                    if(number > 0 && !numberVisible) {
                        drawCircle(
                            Color.Red,
                            5.dp.toPx(),
                            Offset(this.size.width, 0f)
                        )
                    }
                }
        )

        if(number > 0 && numberVisible) {
            Text(
                text = if(number > 99) "99+" else number.toString(),
                modifier = Modifier
                    .layout { measurable, constraints ->
                        val placeable = measurable.measure(constraints)
                        layout(placeable.width, placeable.height) {
                            placeable.placeRelative(iconSize.dp.roundToPx() - placeable.width / 2, -placeable.height/2)
                        }
                    }
                    .drawBehind {
                        drawCircle(
                            Color.Red,
                            8.dp.toPx(),
                            Offset(this.size.width / 2, this.size.height / 2)
                        )
                    },
                style = DemoTheme.typography.badge
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewBadgeIcon(){
    Column {
        BadgeIcon(R.drawable.ic_cassandra, 40, "", 9, true)
        BadgeIcon(R.drawable.ic_cassandra, 40, "", 99, true)
        BadgeIcon(R.drawable.ic_cassandra, 40, "", 100, true)
        BadgeIcon(R.drawable.ic_cassandra, 40, "", 100, false)
    }
}